package com.common.data.desensitization.common.handler;

import com.common.data.desensitization.common.annotation.DesensitizationRule;
import com.common.data.desensitization.common.utils.RepeatMaskUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class DesensitizePhoneHandler implements DesensitizationHandler{
    @Override
    public String desensitize(String originalValue, DesensitizationRule rule) {
        // 138****1234
        if (originalValue.length() == 11) {
            return originalValue.substring(0, 3) + RepeatMaskUtil.repeatMask(4,rule.maskChar()) + originalValue.substring(7);
        }else {// 对于非标准长度，可以采用通用中间打码
            if (originalValue.length() <= 3 + 4) {
                if (originalValue.length() <= 3) return originalValue; //只保留前缀
                return  RepeatMaskUtil.repeatMask(originalValue.length(), rule.maskChar());
            }
            String prefix = originalValue.substring(0, 3);
            String suffix = originalValue.substring(originalValue.length() - 4);
            if (StringUtils.hasText(rule.middleReplaceString())) {
                return prefix + rule.middleReplaceString() + suffix;
            } else {
                int maskedLength = originalValue.length() - 3 - 4;
                return prefix +  RepeatMaskUtil.repeatMask(maskedLength, rule.maskChar()) + suffix;
            }
        }
    }
}
